﻿# Create your views here.
from django.template.loader import get_template
from django.template import Context,RequestContext

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.conf import settings

import traceback,sys

#Ajax new implementation
from django.utils import simplejson
import MySQLdb

from AIB_Monitor.views import get_time_diference
#from django.contrib.auth.models import User

##CHANGE FOR TIME SYNC
gmt_offset_brazil = settings.GMT_OFFSET_BRAZIL
mysql_server_invert_offset = (gmt_offset_brazil/60)*(-1)
######################

###TESTING PURPOSE#############
time_difference_hour = get_time_diference() #somente para teste!!
###############################

def get_graph_ativo(ativo_cod='PETR4', ultimo_time=None, limit_graph=20, template_name='graph_ativo_middle.html'):
	try:
		db = MySQLdb.connect(user = settings.STOCKS_DB_USER, 
							db = settings.STOCKS_DB_NAME, 
							passwd = settings.STOCKS_DB_PASS, 
							host = settings.STOCKS_DB_HOST, 
							port = settings.STOCKS_DB_PORT)
		
		
		
		
		ultimo_time_query = ""
		limit_query = "LIMIT %s" % (str(limit_graph))
		if ultimo_time:
			ultimo_time_query = "AND (UNIX_TIMESTAMP(CONVERT_TZ(`data_hora`,'+00:00','-0%d:00'))*1000) > %s" % ((mysql_server_invert_offset+2),ultimo_time)
			limit_query=""
		
		#PROD
		#'''
		#(SELECT (UNIX_TIMESTAMP(CONVERT_TZ(`data_hora`,'+00:00','-03:00'))*1000) AS unix_hora,CAST(ULTIMO AS CHAR)
		query_select = """
						SELECT * FROM
						(SELECT (UNIX_TIMESTAMP(CONVERT_TZ(`data_hora`,'+00:00','-0%d:00'))*1000) AS unix_hora,CAST(ULTIMO AS CHAR)
						FROM br_stocks_prod
						WHERE ativo_cod = '%s'
						%s
						ORDER BY data_hora DESC
						%s) A 
						ORDER BY A.unix_hora ASC;
						""" % ((mysql_server_invert_offset+2),ativo_cod,ultimo_time_query,limit_query)			
		
		#'''
		#DEV
		'''
		query_select = """
						SELECT * FROM
						(SELECT (UNIX_TIMESTAMP(`data_hora`)*1000) AS unix_hora,CAST(ULTIMO AS CHAR)
						FROM br_stocks_prod
						WHERE ativo_cod = '%s'
						%s
						AND data_hora < DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL %s MINUTE)
						ORDER BY data_hora DESC
						%s) A
						ORDER BY A.unix_hora ASC;
						""" % (ativo_cod,ultimo_time_query,time_difference_hour,limit_query)			
		'''
		#print "query_select: %s" % (query_select)
		cursor = db.cursor()
		cursor.execute(query_select)
		response_dict = {}
		response_dict['response'] = cursor.fetchall()
		response_dict['fields'] = cursor.description
		response_dict['template_name'] = template_name
		response_dict['ativo_cod'] = ativo_cod
		#print "ultimo_time:%s" % (response_dict['ultimo_time'])
		db.close()
		
		#return HttpResponse(simplejson.dumps(response), mimetype='application/json; charset=UTF-8')
		print "response_dict['response'] = %d" % (len(response_dict['response']))
		if len(response_dict['response'])>0:
			response_dict['ultimo_time'] = response_dict['response'][-1][0]
			return response_dict
		else:
			return None
	except:
		exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
		traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
						  limit=2, file=sys.stdout) 

def get_graph_ativo_ajax_html(request,ativo_cod,limit_graph=20):
	try:
		response_dict=get_graph_ativo(ativo_cod=ativo_cod,limit_graph=limit_graph)
		if response_dict:
			t = get_template(response_dict['template_name'])
			c = RequestContext(request,response_dict)
			html = t.render(c)
			return HttpResponse(html, mimetype='text/html; charset=UTF-8')
		else:
			return HttpResponse(simplejson.dumps('UN'), mimetype='application/json; charset=UTF-8')
	except:
		exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
		traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
						  limit=2, file=sys.stdout) 

def get_graph_ativo_ajax_json(request,ativo_cod,ultimo_time,limit_graph=20):
	try:
		#print "ultimo_time:%s" % (ultimo_time)		
		response_dict=get_graph_ativo(ativo_cod=ativo_cod,ultimo_time=ultimo_time,limit_graph=limit_graph)
		if response_dict:
			return HttpResponse(simplejson.dumps(response_dict['response']), mimetype='application/json; charset=UTF-8')
		else:
			return HttpResponse(simplejson.dumps('UN'), mimetype='application/json; charset=UTF-8')
	except:
		exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
		traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
						  limit=2, file=sys.stdout) 				